<template>
    <!-- 广告位管理 -->
    <div class="p-2">
        <!-- 头部搜索框 -->
        <div class="mb-[10px]" v-show="showSearch">
            <el-card shadow="hover">
                <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="85px">
                    <el-form-item label="广告名称" prop="name">
                        <el-input v-model="queryParams.name" placeholder="请输入广告名称" clearable style="width: 240px" />
                    </el-form-item>

                    <el-form-item label="使用场景" prop="scene" style="width: 220px">
                        <el-select v-model="queryParams.scene" placeholder="请选择" clearable>
                            <el-option v-for="dict in advert_scene" :key="dict.value" :label="dict.label"
                                :value="dict.value" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="状态" prop="enable" style="width: 180px">
                        <el-select v-model="queryParams.enable" placeholder="请选择" clearable>
                            <el-option v-for="dict in uingopnse" :key="dict.value" :label="dict.label"
                                :value="dict.value" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="是否为活动" prop="activity" style="width: 180px">
                        <el-select v-model="queryParams.activity" placeholder="请选择" clearable style="width: 240px">
                            <el-option v-for="dict in guonsetui" :key="dict.value" :label="dict.label"
                                :value="dict.value" />
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="handleQuery" icon="Search">搜索</el-button>
                        <el-button @click="resetQuery" icon="Refresh">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
        <!-- 表格和新增修改删除和分页 -->
        <el-card shadow="hover">
            <!-- 新增修改删除按钮 -->
            <template #header>
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleAdd()"
                            v-hasPermi="['system:component:add']">新增</el-button>
                    </el-col>
                    <!-- <el-col :span="1.5">
                        <el-button type="success" plain :disabled="single" icon="Edit"
                            v-hasPermi="['system:component:edit']">修改</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain
                            v-hasPermi="['system:component:delete']">删除</el-button>
                    </el-col> -->
                    <!-- <el-col :span="1.5">
                        <el-button type="warning" plain icon="Download" v-hasPermi="['system:component:export']">导出</el-button>
                    </el-col> -->
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"
                        :search="true"></right-toolbar>
                    <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
                </el-row>
            </template>
            <!-- 列表 -->
            <el-table :data="tableData" v-loading="loading" max-height="550">
                <!-- <el-table-column type="selection" width="55" align="center" /> -->
                <el-table-column prop="name" label="广告名称" align="center" v-if="columns[0].visible" />
                <el-table-column label="使用场景" align="center" v-if="columns[1].visible">
                    <template #default="scope">
                        <dict-tag :options="advert_scene" :value="scope.row.scene" />
                    </template>
                </el-table-column>
                <el-table-column label="类型" align="center" v-if="columns[2].visible">
                    <template #default="scope">
                        <span v-if="scope.row.actionType == 'H5'">
                            h5
                        </span>
                        <span v-if="scope.row.actionType == 'NATIVE'">
                            客户端原生页面
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="actionUrl" label="链接地址" align="center" v-if="columns[3].visible" />
                <el-table-column prop="intro" label="链接描述" align="center" :show-overflow-tooltip="true" v-if="columns[4].visible" />
                <el-table-column label="排序" prop="sort" align="center" v-if="columns[5].visible" />
                <el-table-column label="广告图片" align="center" v-if="columns[6].visible">
                    <template #default="scope">
                        <el-image style="width: 100px; height: 100px"
                            :src="scope.row.sourceUrl "
                            :preview-src-list="[scope.row.sourceUrl]" fit="contain" :preview-teleported="true" />
                    </template>
                </el-table-column>
                <el-table-column label="是否活动" align="center" v-if="columns[7].visible">
                    <template #default="scope">
                        <span v-if="scope.row.activity == 1">
                            是
                        </span>
                        <span v-if="scope.row.activity == 0">
                            否
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="上线/下线" align="center" v-if="columns[8].visible">
                    <template #default="scope">
                        <el-switch @change="handleStatusChange(scope.row)" :active-value="1" :inactive-value="0"
                            v-model="scope.row.enable">
                        </el-switch>
                    </template>
                </el-table-column>

                <el-table-column fixed="right" label="操作" width="180" align="center">
                    <template #default="scope">
                        <el-tooltip content="修改" placement="top">
                            <el-button link type="primary" @click="handleUpdate(scope.row)" icon="Edit"
                                v-hasPermi="['system:component:edit']"></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                                v-hasPermi="['system:component:remove']"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>
        <!-- 添加弹窗 -->
        <el-dialog :title="huinseo.title" v-model="huinseo.visible" width="500px" append-to-body>
            <el-form ref="roleFormRef" :model="huoinsinfrom" :rules="rules" label-width="110px">
                <el-form-item label="广告名称：" prop="name">
                    <el-input v-model="huoinsinfrom.name" placeholder="请输入广告名称"></el-input>
                </el-form-item>
                <el-form-item label="使用场景：" prop="scene">
                    <el-select v-model="huoinsinfrom.scene" placeholder="请选择使用场景" clearable style="width: 100%;">
                        <el-option v-for="item in advert_scene" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="链接类型：" prop="actionType">
                    <el-select v-model="huoinsinfrom.actionType" placeholder="请选择使用类型" clearable style="width: 100%;">
                        <el-option v-for="item in guoeuiguon" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="链接地址：" prop="actionUrl">
                    <el-input v-model="huoinsinfrom.actionUrl" placeholder="请输入链接地址"></el-input>
                </el-form-item>
                <el-form-item label="链接描述：" prop="intro">
                    <el-input v-model="huoinsinfrom.intro" placeholder="请输入链接描述"></el-input>
                </el-form-item>
                <el-form-item label="是否为活动：" prop="activity">
                    <el-radio-group v-model="huoinsinfrom.activity">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否启用：" prop="enable">
                    <el-radio-group v-model="huoinsinfrom.enable">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="广告图片：" prop="sourceUrl">
                    <el-upload class="avatar-uploader" :action="huonseom.url" :headers="huonseom.headers"
                        :show-file-list="false" :on-success="handleAvatarSuccess">
                        <img v-if="huoinsinfrom.sourceUrl" :src="huoinsinfrom.sourceUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>

                    <!-- <el-upload class="avatar-uploader" action="#" :http-request="ossUploadFileHandle"
                        :show-file-list="false">
                        <img v-if="huoinsinfrom.sourceUrl" :src="huoinsinfrom.sourceUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload> -->
                </el-form-item>
                <el-form-item label="排序：" prop="sort">
                    <el-input-number v-model="huoinsinfrom.sort" controls-position="right" :min="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="huonseuinh(roleFormRef)" type="primary">确 定</el-button>
                    <el-button @click="cancelDataScope">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 修改弹窗 -->
        <el-dialog :title="xuongui.title" v-model="xuongui.visible" width="500px" append-to-body>
            <el-form ref="ronmseuin" :model="monseuoinh" :rules="rionmse" label-width="110px">
                <el-form-item label="广告名称：" prop="name">
                    <el-input v-model="monseuoinh.name" placeholder="请输入广告名称"></el-input>
                </el-form-item>
                <el-form-item label="使用场景：" prop="scene">
                    <el-select v-model="monseuoinh.scene" placeholder="请选择使用场景" clearable style="width: 100%;">
                        <el-option v-for="item in advert_scene" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="链接类型：" prop="actionType">
                    <el-select v-model="monseuoinh.actionType" placeholder="请选择使用类型" clearable style="width: 100%;">
                        <el-option v-for="item in guoeuiguon" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="链接地址：" prop="actionUrl">
                    <el-input v-model="monseuoinh.actionUrl" placeholder="请输入链接地址"></el-input>
                </el-form-item>
                <el-form-item label="链接描述：" prop="intro">
                    <el-input v-model="monseuoinh.intro" placeholder="请输入链接描述"></el-input>
                </el-form-item>
                <el-form-item label="是否为活动：" prop="activity">
                    <el-radio-group v-model="monseuoinh.activity">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否启用：" prop="enable">
                    <el-radio-group v-model="monseuoinh.enable">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="广告图片：" prop="sourceUrl">
                    <el-upload class="avatar-uploader" :action="huonseom.url" :headers="huonseom.headers"
                        :show-file-list="false" :on-success="huonseunco">
                        <img v-if="monseuoinh.sourceUrl" :src="monseuoinh.sourceUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>

                    <!-- <el-upload class="avatar-uploader" action="#" :http-request="lonseuinoneu" :show-file-list="false">
                        <img v-if="monseuoinh.sourceUrl" :src="monseuoinh.sourceUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload> -->
                </el-form-item>
                <el-form-item label="排序：" prop="sort">
                    <el-input-number v-model="monseuoinh.sort" controls-position="right" :min="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="huonsetui(ronmseuin)" type="primary">确 定</el-button>
                    <el-button @click="huonseuint">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="Advert">
// import upload from "@/utils/upload";
import { listCompon, addComponent, delComponent, enableAdvert, updateComponent } from '@/api/system/advert/index';
// 添加修改弹窗的参数
import type { FormInstance } from 'element-plus'
// 获取toke的方法
import { globalHeaders } from "@/utils/request";
// 引用数据字典
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { advert_scene } = toRefs<any>(proxy?.useDict('advert_scene'));

const huonseom = reactive<UploadOption>({
    headers: globalHeaders(),
    url: import.meta.env.VITE_APP_BASE_API + '/file/upload'
})
// 搜索查询参数
const total = ref(0)
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    name: '',
    scene: '',
    enable: '',
    activity: '',
})
const queryFormRef = ref()
// 列表多选中的列参数
const ids = ref<Array<string | number>>([])
const single = ref(true)

const roleFormRef = ref<FormInstance>();

const ronmseuin = ref<FormInstance>();

const huinseo = reactive({
    visible: false,
    title: ''
});

const xuongui = reactive({
    visible: false,
    title: ''
});

const huoinsinfrom = reactive({
    name: "",
    scene: "",
    actionType: "",
    actionUrl: "",
    intro: "",
    activity: 0,
    enable: 1,
    sourceUrl: "",
    sort: 0,
})

const monseuoinh = reactive({
    id: "",
    name: "",
    scene: "",
    actionType: "",
    actionUrl: "",
    intro: "",
    activity: 0,
    enable: 1,
    sourceUrl: "",
    sort: 0,
})
const rules = reactive({
    name: [{ required: true, message: "广告名称不能为空", trigger: "blur" }],
    scene: [{ required: true, message: "使用场景不能为空", trigger: "blur" }],
    actionType: [{ required: true, message: "链接类型不能为空", trigger: "blur" }],
    actionUrl: [{ required: true, message: "链接地址不能为空", trigger: "blur" }]
})

const rionmse = reactive({
    name: [{ required: true, message: "广告名称不能为空", trigger: "blur" }],
    scene: [{ required: true, message: "使用场景不能为空", trigger: "blur" }],
    actionType: [{ required: true, message: "链接类型不能为空", trigger: "blur" }],
    actionUrl: [{ required: true, message: "链接地址不能为空", trigger: "blur" }]
})
// 表格参数
const tableData = ref([]);
// 加载中
const loading = ref(false);
// 动态表格控制显隐参数
const showSearch = ref(true);
// 列显隐信息
const columns = ref([
    { key: 0, label: `广告名称`, visible: true, children: [] },
    { key: 1, label: `使用场景`, visible: true, children: [] },
    { key: 2, label: `类型`, visible: true, children: [] },
    { key: 3, label: `链接地址`, visible: true, children: [] },
    { key: 4, label: `链接描述`, visible: true, children: [] },
    { key: 5, label: `排序`, visible: true, children: [] },
    { key: 6, label: `广告图片`, visible: true, children: [] },
    { key: 7, label: `是否活动`, visible: true, children: [] },
    { key: 8, label: `上线/下线`, visible: true, children: [] }
])
// 广告位搜索状态
const uingopnse = ref([
    {
        value: 1,
        label: '启用'
    }, {
        value: 0,
        label: '禁用'
    }
])
// 广告位搜索是否活动
const guonsetui = ref([
    {
        value: 1,
        label: '是'
    }, {
        value: 0,
        label: '否'
    }
])
// 广告位搜索弹窗的链接类型
const guoeuiguon = ref([
    {
        value: 'H5',
        label: 'h5'
    }, {
        value: 'NATIVE',
        label: '客户端原生页面'
    }
])
/** 查询菜单列表 */
const getList = () => {
    loading.value = true;
    listCompon(queryParams).then(res => {
        if (res.code == 200) {
            // console.log(res);
            tableData.value = res.data.list;
            total.value = res.data.total;
            loading.value = false;
        }
    });
}
/** 添加广告弹窗 */
const handleAdd = () => {
    huinseo.visible = true;
    huinseo.title = "添加广告位";
}
/* 确认按钮（添加）*/
const huonseuinh = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            addComponent(huoinsinfrom).then(res => {
                if (res.code == 200) {
                    // console.log(res);
                    proxy?.$modal.msgSuccess("添加成功");
                    getList();
                    roleFormRef.value?.resetFields();
                    huinseo.visible = false;
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
/* 取消按钮（添加）*/
const cancelDataScope = () => {
    roleFormRef.value?.resetFields();
    huinseo.visible = false;
}
/** 修改广告 */
const handleUpdate = async (row: any) => {
    // console.log(row);
    xuongui.visible = true;
    xuongui.title = "修改广告位";
    monseuoinh.id = row.id;
    monseuoinh.name = row.name;
    monseuoinh.scene = row.scene;
    monseuoinh.actionType = row.actionType;
    monseuoinh.actionUrl = row.actionUrl;
    monseuoinh.activity = row.activity;
    monseuoinh.enable = row.enable;
    monseuoinh.sourceUrl = row.sourceUrl;
    monseuoinh.sort = row.sort;
    monseuoinh.intro = row.intro;
}
/* 确认按钮（修改）*/
const huonsetui = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            updateComponent(monseuoinh).then(res => {
                if (res.code == 200) {
                    // console.log(res);
                    proxy?.$modal.msgSuccess("修改成功");
                    getList();
                    ronmseuin.value?.resetFields();
                    xuongui.visible = false;
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
/* 取消按钮（修改）*/
const huonseuint = () => {
    ronmseuin.value?.resetFields();
    xuongui.visible = false;
}
// 添加弹窗的图片上传
const handleAvatarSuccess = (res: any) => {
    // console.log(res);
    // 如果上传成功
    if (res.code === 200) {
        huoinsinfrom.sourceUrl = res.data.url.replace('juguanghe.oss-cn-hangzhou.aliyuncs.com', 'oss.fengjuhe.com');
    } else {
        proxy?.$modal.loading(res.msg);
    }
}
// 修改弹窗的图片上传
const huonseunco = (res: any) => {
    //如果上传成功
    if (res.code === 200) {
        monseuoinh.sourceUrl = res.data.url.replace('juguanghe.oss-cn-hangzhou.aliyuncs.com', 'oss.fengjuhe.com');
    } else {
        proxy?.$modal.loading(res.msg);
    }
}


// 添加的自定义图片上传
// const ossUploadFileHandle: any = (op: any) => {
//     // console.log(op);
//     upload(op.file).then((res: any) => {
//         // console.log(res);
//         huoinsinfrom.sourceUrl = res;
//     });
// };
// 修改的自定义图片上传
// const lonseuinoneu: any = (op: any) => {
//     // console.log(op);
//     upload(op.file).then((res: any) => {
//         // console.log(res);
//         monseuoinh.sourceUrl = res;

//     });
// };

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
}

/**删除按钮操作 */
const handleDelete = (row: any) => {
    if (row.enable == 0) {
        ElMessageBox.confirm(
            '确认删除该广告吗',
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                draggable: true,
            }
        ).then(async () => {
            await delComponent(row.id);
            getList();
            proxy?.$modal.msgSuccess('删除成功');
        }).catch(() => { })
    } else {
        proxy?.$modal.msgError('请先执行禁用操作');
    }
}

/** 列表广告状态修改 */
const handleStatusChange = async (row: any) => {
    let text = row.enable == "1" ? "启用" : "停用";
    try {
        await proxy?.$modal.confirm('是否要修改上线/下线状态?');
        await enableAdvert(row.id, { scene: row.scene });
        getList();
        proxy?.$modal.msgSuccess(text + "成功");
    } catch {
        getList();
    }
}
onMounted(() => {
    getList();
})
</script>

<style lang="scss" scoped>
.avatar {
    width: 150px;
    height: 150px;
    display: block;
    object-fit: contain;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    text-align: center;
}
</style>
